<?php
/**
 *Administra las empresas del sitio web
 *@author Luis Gabriel Rodriguez <luisgabriel84@gmail.com>
 */

/**
 *Administra las empresas del sitio web
 */
class ProductsController extends AppController {

	var $name = 'Products';
        /**
        * @var array
        * @access public
        */
	var $helpers = array('Html', 'Form', 'Javascript', 'Flash', 'Time', 'Ajax','Fck');
        /**
        * @var array
        * @access public
        */
	var $components = array('RequestHandler','Cookie','Session','Filehandler');


        function beforeFilter()
        {
            //$this->Auth->allow('ver_categoria','view','get_cities');
        
            $this->Auth->allow('changestado','cleardep','ver_categoria','view','buscar','getCities');

        }
        /**
         * Permite seleccionar el departamento dependiendo de la variable de
         * sesion especificada por el usuario
         *
         * @param integer $dep Id del departamento
         */
        function changestado( $dep )
        {
            $departamentos =
            array(
                'amazonas'=>1,
                'antioquia'=>2,
                'arauca'=>3,
                'atlantico'=>4,
                'bolivar'=>6,
                'boyaca'=>7,
                'caldas'=>8,
                'caqueta'=>9,
                'casanare'=>10,
                'cauca'=>11,
                'cesar'=>12,
                'choco'=>13,
                'cordoba'=>14,
                'cundinamarca'=>15,
                'guainia'=>16,
                'guaviare'=>17,
                'huila'=>18,
                'laguajira'=>19,
                'magdalena'=>20,
                'meta'=>21,
                'narino'=>22,
                'nortedesantander'=>23,
                'putumayo'=>24,
                'quindio'=>25,
                'risaralda'=>26,
                'sanandres'=>27,
                'santander'=>28,
                'sucre'=>29,
                'tolima'=>30,
                'valle'=>31,
                'vaupes'=>32,
                'vichada'=>33
                );
            $state_name = $this->Product->State->findById($departamentos[$dep],array('fields'=>'name'));

            $this->Session->write('Config.dep_name',$state_name['State']['name']);
            $this->Session->write('Config.dep',$departamentos[$dep]);
            $this->Cookie->write('departamento', $departamentos[$dep], null, '+1 day');
            $this->redirect('/');
        }

        /**
         * Elimina la variable de session del departamento
         */

        function cleardep()
        {
            $this->Session->del('Config.dep');
            $this->Session->del('Config.dep_name');
            $this->redirect('/');
        }
	
        /**
         *
         * Muestra las empresas de una categoria en particular
         * @param string $slug identificador alfanumerico de la categoria
         */
	
	function ver_categoria( $slug )
	{
		$this->Producto->recursive =1;
		if(empty( $slug) )
		{
			$this->redirect(array('action'=>'index'));
		}
                $config = $this->Session->read('Config');
                if(array_key_exists('dep', $config))
                {
                    $this->paginate['conditions'] = array('Product.state_id'=>$config['dep']);
                }
                
		$this->paginate['limit'] = 5;
                $this->Product->Category->recursive=0;
		$id = $this->Product->Category->findBySlug($slug, array('id', 'parent_id','name','slug'));
		
                $main_cat = $this->Product->Category->findById($id['Category']['parent_id'], array('name'));
		$empresas = $this->paginate('Product',array('Product.category_id'=>$id['Category']['id']));		
		$this->set('empresas',$empresas);
                $this->set('slug',$id['Category']['slug']);
                $this->set('subcat',$id['Category']['name']);

	
	}
        /**
         *
         * Muestra una empresa en particular dependiendo de su identificador
         * @param integer $slug Identificador alfanumerico
         */
	
	function view($slug = null)
	{
		if (!$slug) {
			$this->Session->setFlash(__('Invalid Product.', true));
			$this->redirect(array('action'=>'index'));
		}
		$id = $this->Product->findBySlug($slug,array('fields'=>'id'));
		$this->set('product', $this->Product->read(null, $id['Product']['id']));
	}
	
        /**
         *
         * Obtiene el listado de ciudades para el cuadro de busqueda
         */
	function getCities() {
		$this->set('options',
			$this->Product->City->find('list',
				array(
					'conditions' => array(
						'City.state_id' => $this->data['Product']['state_id']
					),'order'=>'City.name Asc'
					
				)
			)
		);
		$this->render('/cities/ajax_dropdown');
	}

        /**
         *
         * Permite buscar empresas dependiendo de la palabra clave especificada por el usuario
         */
	
	function buscar()
	{
	    
               if(!empty($this->data['Product']['buscar']))
		{
                    
                    $string = $this->data['Product']['buscar'];
                    $string = strtolower( trim($string) );

                    $palabras = explode(" ", $string);
                    $resultados =array();
                    foreach($palabras as $cadena)
                    {



                        $count =strlen($cadena) ;
                        $raw =$cadena;
                        if ($cadena[$count-1]=='s' && $cadena[$count-2]=='e')
                        {
                                if($cadena[$count-3]!='c'&& $cadena[$count-3]!='l')
                                {
                                    $cadena = substr($cadena,0, -2);
                                }
                                else
                                {
                                    if($cadena[$count-3]!='i'&&$cadena[$count-3]!='l')
                                    {
                                        $cadena = substr($cadena,0,-3).'z';
                                    }
                                }
                        }

                        $inflector = new Inflector();
                        $cadena = $inflector->singularize($cadena);

                        $conditions =
                        array('or' => array('LOWER(Product.nombre_empresa) LIKE' => "%{$cadena}%",'LOWER(Product.nombre_empresa) LIKE' => "%{$raw}%",'LOWER(Product.descripcion) LIKE' => "%{$raw}%"));
                        $this->Product->recursive=1;
                        $search[] = $this->Product->find('all',array( 'conditions'=>$conditions));


                    }

		}
                else
		{
			$this->set('message','Por favor ingrese un criterio de búsqueda');

		}
                
                $this->set('empresas', $search);
	}

        /**
         *
         * Listado de ciudades en el admin
         */
	function admin_index() 
	{
            if(!$this->Acces->check_resctriction(1))
            {
                $this->redirect('/promociones');
            }
	    $this->layout = 'admin';
		$this->Product->recursive = 0;
		$this->set('products', $this->paginate());
	}

        /**
         *
         * Ver una empresa, seccion administrativa
         * @param integer $id Identificador de la empresa
         */
	function admin_view($id = null) 
	{
            if(!$this->Acces->check_resctriction(1))
            {
                $this->redirect('/promociones');
            }
		if (!$id) {
			$this->Session->setFlash(__('Invalid Product.', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->set('product', $this->Product->read(null, $id));
	}

        /**
         *
         * Agrega una nueva empresa
         */
	function admin_add() {
            if(!$this->Acces->check_resctriction(1))
            {
                $this->redirect('/promociones');
            }
	    $this->layout = 'admin';
		if (!empty($this->data)) {
			$this->Product->create();
			
			// subir el logo de la empresa
			if(!empty( $this->data['Product']['imagen']['name'] ))
			{
                            $this->data['Product']['imagen']=$this->Filehandler->uploadpicture('img/empresas/',$this->data['Product']['imagen'],120);
				
			}
			else
                         {
                            $this->data['Product']['imagen'] ='no-photo.jpg';
                          }
			// fin subir logo
			
			
			//subir archivo
			if( !empty( $this->data['Product']['file']['name'] ) )
			{
			    $file = $this->data['Product']['file']  = $this->subir_archivo('files/archivos_empresas/', $this->data['Product']['file']);
			}
			else
                        {
                            $this->data['Product']['file'] ='';
                        }
			
			// fin subir archivo
			
			$this->data['Product']['slug'] = $this->slug( $this->data['Product']['nombre_empresa'] );

			if ($this->Product->save($this->data)) {
				$this->Session->setFlash(__('The Product has been saved', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The Product could not be saved. Please, try again.', true));
			}
		}
		
		$states = $this->Product->State->find('list');
		$cities = $this->Product->City->find('list');
		$categories = $this->Product->Category->find('list',array('conditions'=>array('parent_id >'=>0)));
		$this->set('states',$states );
		$this->set('cities',$cities);
		$this->set(compact('categories'));
	}
    

        /**
         *Modifica una empresa
         *@param integer $id Identificador de la empresa
         */
	function admin_edit($id = null) {
                        if(!$this->Acces->check_resctriction(1))
            {
                $this->redirect('/promociones');
            }

	    $this->layout = 'admin';
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid Product', true));
			$this->redirect(array('action'=>'index'));
		}
		
		if (!empty($this->data)) {
		
		    //Inicia actualizacicion de foto			
		    $this->data_update = $this->Product->read(null, $id);
			if( !empty($this->data['Product']['imagen']['name']))
                        {
                            $this->Filehandler->deleteFile('img/empresas/',$this->data_update['Product']['imagen']);
			    $this->data['Product']['imagen'] = $this->Filehandler->uploadpicture('img/empresas/',$this->data['Product']['imagen'],120);
				
			}
			else
			{
			    $this->data['Product']['imagen'] = $this->data_update['Product']['imagen']; 
			}
			//FIN actualizacicion de foto
	
			//subir archivo
			if( !empty( $this->data['Product']['file']['name'] ) )
			{
			    $file = $this->data['Product']['file']  = $this->Filehandler->upload_single_file('files/archivos_empresas/', $this->data['Product']['file']);
			}
			else
                        {
                            $this->data['Product']['file'] =$this->data_update['Product']['file']; ;
                        }
			
			// fin subir archivo
                        $this->data['Product']['slug'] = $this->slug( $this->data['Product']['nombre_empresa'] );
			if ($this->Product->save($this->data)) {
				$this->Session->setFlash(__('El Product ha sido guardado', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The Product could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Product->read(null, $id);
		}
		
                $states = $this->Product->State->find('list');
		$cities = $this->Product->City->find('list');
		$categories = $this->Product->Category->find('list',array('conditions'=>array('parent_id >'=>0)));
		$this->set(compact('categories'));
                $this->set('states',$states );
		$this->set('cities',$cities);
	}
	
        /**
         *
         * Elimina una empresa
         * @param integer $id Identificador de la empresa
         */
	
	function admin_delete($id = null)
        {
            if(!$this->Acces->check_resctriction(1))
            {
                $this->redirect('/promociones');
            }
	    $this->layout = 'admin';
            if (!$id)
            {
                    $this->Session->setFlash(__('Invalid id for Product', true));
                    $this->redirect(array('action'=>'index'));
            }
		
		//inicia eliminar archivo
            $this->data_update = $this->Product->read(null, $id);
	    $foto = $this->data_update['Product']['imagen']; 
			    
	    if( file_exists( WWW_ROOT .'empresas/'.$foto) && $foto != "" )
	    {
			unlink(WWW_ROOT .'empresas/'.$foto);
	    }
			    
	    if( file_exists( WWW_ROOT .'empresas/thumbs/'.$foto) && $foto != "" )
	    {
			unlink(WWW_ROOT .'empresas/thumbs/'.$foto);
	    }
            //fin eliminar archivo
		if ($this->Product->del($id)) {
			$this->Session->setFlash(__('Product Eliminado', true));
			$this->redirect(array('action'=>'index'));
		}
	}
}
?>